(function(window) {
	var browser = {
	        versions : function() {
	            var u = navigator.userAgent, app = navigator.appVersion;
	            return {//移动终端浏览器版本信息
	                trident : u.indexOf('Trident') > -1, //IE内核
	                presto : u.indexOf('Presto') > -1, //opera内核
	                webKit : u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
	                gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
	                mobile : !!u.match(/AppleWebKit.*Mobile.*/)
	                || !!u.match(/AppleWebKit/), //是否为移动终端
	                ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
	                android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
	                iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
	                iPad : u.indexOf('iPad') > -1, //是否iPad
	                webApp : u.indexOf('Safari') == -1
	                //是否web应该程序，没有头部与底部
	            };
	        }(),
	        language : (navigator.browserLanguage || navigator.language).toLowerCase()
	};
	
	
	var imagePath = basePath + '/resource/images/';
	
	String.prototype.trim=function()
	{
	     return this.replace(/(^\s*)|(\s*$)/g, "");
	}
	
	// 载入收藏信息

	
	
	var util = {
		isNullOrEmpty : function(val) {
			return val == null || val == undefined || val == "";
		},
		getQueryString : function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			var r = window.location.search.substr(1).match(reg);
			if (r != null)
				return unescape(r[2]);
			return null;
		}
	};
	var TemCache = {
		set : function(key, val) {
			if (util.isNullOrEmpty(key)) // util.isNullOrEmpty(val) ||
				return false;

			localStorage.setItem(key, JSON.stringify(val));
			return true
		},
		get : function(key) {
			return JSON.parse(localStorage.getItem(key));
		}
	};

	var bHid = 0;
	var fn = {
		// 获取天气信息
		getWeathers : function(callBackFn) {
		},
		
		initLocalData : function(){
			// 初始化导航栏信息
			var collectionData = TemCache.get('collection_LDD');
			var collectionArray = [
			    				{"link":"http://www.vrv.com.cn","title":"北信源","isDelFlag":"0","isShowFlag":"1"},
			    				{"link":"http://www.baidu.com","title":"百度","isDelFlag":"1","isShowFlag":"1"},
			    				{"link":"http://www.sina.com.cn","title":"新浪","isDelFlag":"1","isShowFlag":"1"},
			    				{"link":"http://www.sohu.com","title":"搜狐","isDelFlag":"1","isShowFlag":"1"},
			    				{"link":"http://www.163.com","title":"网易","isDelFlag":"1","isShowFlag":"1"}
			    				];
			if(collectionData == null){
				TemCache.set('collection_LDD', collectionArray);
			}else{
				for(var i in collectionData){
					if(collectionData[i].isShowFlag == undefined){
						collectionData[i].isShowFlag = "1";
						collectionData[i].isDelFlag = "1";
					}
					if(collectionData[i].link == "http://www.vrv.com.cn"){
						collectionData[i].isDelFlag = "0";
					}
				}
				TemCache.set('collection_LDD',collectionData);
				for(var i in collectionArray){
					var flag = true;
					for(var j in collectionData){
						if(collectionData[j].link == collectionArray[i].link){
							flag = false;
							break;
						}
					}
					if(flag){
						collectionData.push(collectionArray[i]);
						TemCache.set('collection_LDD',collectionData);
					}
				}
			}
		},

		toWeatherRecord : function(he) {
		},

		// 获取集合信息
		getLocalData : function(callBackFn) {
			var colle = TemCache.get('collection_LDD');
			callBackFn && callBackFn.call(this, colle);
		},

		deleteCollectionItem : function(url, title) {
			var colle = TemCache.get('collection_LDD') || [];
			var colle2 = [];
			for (var i = 0; i < colle.length; i++) {
				if (colle[i].link == url && colle[i].title == title) {
					// colle.splice(i, 1);
					// break;
					// console.info("equ");
					// console.info(colle[i]);
					colle[i].isShowFlag = "0";
					colle2.push(colle[i]);
				} else {
					// console.info("not equ");
					// console.info(colle[i]);
					colle2.push(colle[i]);
				}
			}
			TemCache.set('collection_LDD', colle2);
		},
		
		// 载入收藏信息
		loadToView_Collection : function(colleData) {
			if (util.isNullOrEmpty(colleData))
				return;

			var colleHtml = "";
			for ( var i in colleData) {
				colleHtml += this.getColleHtmlByColleData(colleData[i]);
			}
			if($('.link').length == 0){
				$('#colleList').html(colleHtml);
			}else{
				$('.link:last').after(colleHtml);
			}
		},

		// 根据给定的数据组织收藏文件的html
		getColleHtmlByColleData : function(colleData) {
			if(colleData.isShowFlag == 1){
				var strUrl = colleData.link.replace(/\./g,"_");
				if (strUrl.indexOf("http://") == 0 || strUrl.indexOf("https://") == 0){
					strUrl = strUrl.replace("http://","");
					strUrl = strUrl.replace("https://","");
				}
				// console.log( )
				var colleHtml = "";
				colleHtml += '<li class="link" linkUrl="'+colleData.link+'" onclick="showIframe(\''+colleData.link+"')"
				+ '" data-title="' + colleData.title + '">';
				// colleHtml += '<div class="collec-top"><img src="' +
				// colleData.link
				// + "/favicon.ico" + '" alt=""></div>';
				colleHtml += '<div class="collec-top"><img class="rotate" src="'
						+ basePath+'/resource/images/navigation/'
						+ strUrl
						+ ".png"
						//+ colleData.link
						//+ "/favicon.ico"
						// + '" alt="" onerror="this.onerror=null;this.style.display
						// = \'\';this.src=\'1x1.png\';this.className=\'bg\'">';
						+ '" alt="" onerror="this.onerror=null;this.src=\''+ basePath + '/resource/images/navigation/default01.png\';">';
				//isDelFlag:0  不允许删除  1：可以删除
				if(colleData.isDelFlag == 1){
					colleHtml += '<div class="deleteTag" style="visibility:hidden"><span class="glyphicon glyphicon-remove bg " role="menuitem" tabindex="-1"></span></div>';
				}
				colleHtml += '</div>';
				colleHtml += '<div class="collec-bottom">' + colleData.title
						+ '</div>';
				// colleHtml += '<i class="icon-search"></i>';
				colleHtml += '</li>';
				return colleHtml;
			}else{
				return "";
			}
		},

		// 保存收藏信息
		saveCollection : function() {
			var title = $('#txtTitle').val().trim(), url = $("#txtUrl").val().trim();

			if (util.isNullOrEmpty(url) && util.isNullOrEmpty(title)){
				window.modalAlert(messages.writeTitleAndUrl);
				return;
			}

			if (util.isNullOrEmpty(url) || url.indexOf(".") <= 0) {
				window.modalAlert(messages.pleaseWriteUrl);
				// $("#tpTitle").popover("show");
				// $("#lblCollectDialogInfo").html("要输入网址");
				// $("#myModal .alert-warning").alert();
				return;
			}
			if (url.indexOf("http://") < 0 && url.indexOf("https://") < 0)
				url = "http://" + url;

			if (util.isNullOrEmpty(title)) {
				window.modalAlert(messages.pleaseWriteTitle);
				return;
			}

			var collection = {
				'link' : url,
				'title' : title,
				'isDelFlag':'1',
				'isShowFlag':'1'
			}, collectionData = TemCache.get('collection_LDD') || [];

			var repeatedIdx = -1;
			for (var i = 0; i < collectionData.length; i++) {
				if (collectionData[i].link == url
						|| collectionData[i].title == title) {
					repeatedIdx = i;
					break;
				}
			}
			if (repeatedIdx != -1) {
				if(collectionData[repeatedIdx].isShowFlag == 0){
					collectionData[repeatedIdx].isShowFlag = "1";
				}else if(!confirm(messages.isCover))
					return;
			}

			if (repeatedIdx == -1){
				collectionData.push(collection);
			}
			else {
				collectionData[repeatedIdx] = collection;				
			}			

			if (TemCache.set('collection_LDD', collectionData)) {
				$('#myModal').modal('hide');
				$('#txtTitle').val('');
				$('#txtUrl').val('');
				
				$('#colleList li').remove();
				//$('#btnAdd').before(this.getColleHtmlByColleData(collection));				
				this.loadToView_Collection(collectionData);
			}
		},

		deleteAndReshow : function() {
			this.deleteCollectionItem(_g_d_w_url, _g_d_w_title);
			// fn.deleteCollectionItem(url3, title3);
			rotate_stop();
			this.deleteTagShow();

			// 重新加载
			$('#colleList li').remove();
			this.getLocalData(function(data) {
				if (!data)
					return;
				this.loadToView_Collection(data);

			});
		},

		deleteTagShow : function() {
			$("#colleList .deleteTag").css("visibility", "visible");
			$("#colleList img").css("cursor", "default");
		},
		deleteTagHide : function() {
			$("#colleList .deleteTag").css("visibility", "hidden");
			$("#colleList img").css("cursor", "pointer");
		},

		handlerWeathDisplay : function(callbackHide, callbackShow) {
			var _this = this;
			if (bHid) {
				bHid = 0;
				callbackShow && callbackShow.call(_this);
			} else {
				bHid = 1;
				callbackHide && callbackHide.call(_this);
			}
		},

		getLocalCity : function() {
			var city = TemCache.get('localCity') || "";
			return city;
		},

		saveCity : function(city) {
			return TemCache.set('localCity', city);
		},

		isLastWeatherOk : function() {
			var t = fn.getLastWeatherTime();
			if (util.isNullOrEmpty(t))
				return false;
			var now = new Date().getTime();
			if (now - t > window.g_weather_cache_second * 1000)
				return false; // 缓存时间
			if (util.isNullOrEmpty(fn.getLastWeather()))
				return false;
			return true;
		},
		

		initCitiesData0 : function() {
			// 初始化城市数据
			if (!window.chinaCities) {
				var cts = str_ChinaCities.split("\n");
				for (var i = cts.length - 1; i >= 0; i--) {
					var line = cts[i].split("\t");
					var city = {
						"regionName" : line[2],
						"regionNameEn" : line[1],
						"regionCode" : line[0],
						"city" : line[3],
						"region" : line[4]
					};
					cts[i] = city;
				}
				window.chinaCities = cts;
			}
		},

		setForSelectCity0 : function() {
			$('#autocompleteInput')
					.autocomplete(
							{
								"source" : function(query, process) {
									/*
									 * var matchCount = this.options.items;//
									 * 返回结果集最大数量 $.get("region.json", {
									 * "matchInfo" : query, "matchCount" :
									 * matchCount }, function(respData) { return
									 * process(respData); });
									 */

									fn.initCitiesData0();

									var matchCount = this.options.items || 10;
									var cityCount = window.chinaCities.length;
									var matchCities = [];
									for (var i = 0; i < matchCount; i++) {
										var city = window.chinaCities[i];
										if (city.regionName.indexOf(query) >= 0
												|| city.regionNameEn
														.indexOf(query) >= 0
												|| city.city.indexOf(query) >= 0
												|| city.region.indexOf(query) >= 0) {
											matchCities.push(city);
										}
									}
									// process(matchCities);
									process(window.chinaCities);
								},
								"formatItem" : function(item) {
									return item["regionName"] + "("
											+ item["regionNameEn"] + "，"
											+ item["city"] + "，"
											+ item["region"] + ") - "
											+ item["regionCode"];
								},
								"setValue" : function(item) {
									return {
										'data-value' : item["regionName"],
										'real-value' : item["regionCode"]
									};
								}
							});

		},

		initCitiesData : function() {
			// 初始化城市数据
			if (!window.chinaCities) {
				var cts = window.aryCities;
				var ctsObj = [];
				for (var i = cts.length - 1; i >= 0; i--) {
					var line = cts[i].split("\t");
					var city = {
						// "regionName" : line[2] + "(" + line[1] + ")" + "-"
						// + line[3] + "-" + line[4] + " " + line[0]
						// ,"regionName" : line[2]
						// ,"regionNameEn" : line[1]
						"regionNameChEn" : line[2] + " " + line[1],
						"regionCode" : line[0]
					// "city" : line[3]
					// "region" : line[4]
					};
					ctsObj.push(city);
				}
				window.chinaCities = ctsObj;

			}

		},

		setForSelectCity : function() {
			fn.initCitiesData();
			$('#autocompleteInput').typeahead({
				"source" : window.chinaCities,
				"display" : "regionName", // 默认的对象属性名称为 name 属性
				"val" : "regionCode", // 默认的标识属性名称为 id 属性
				"items" : 8, // 最多显示项目数量
				"itemSelected" : function(item, val, text) { // 当选中一个项目的时候，回调函数
					window.selectedCity = item;
					alert(item);
				},

				// 让 bootstrap typeahead 支持复杂对象数据源
				// http://www.tuicool.com/articles/RbmqEj
				minLength : 1

				,
				labeler : [ 'regionNameChEn' ] // ['regionName',
				// 'regionNameEn']//
				// 下拉列表需要显示的对象属性
				,
				propName : 'regionNameChEn' // 用来匹配搜索的对象属性，默认是对象的value属性，依然支持单值数据源，只需要把这个属性设置为''
				,
				updater : function(item) {
					return item.split(' ')[0];
				}
			});

		},

		loadShareImages : function() {

			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			$.ajax({
				"type" : "GET",
				"url" : basePath + "/attention/getSharePhoto.do",// window.g_share_json_url,
				"data" : {
					"userid" : userToken,
					"userToken":userToken,
					"lang":lang
				},
				// "dataType" : "json",
				"success" : function(j) {
					if (util.isNullOrEmpty(j))
						return;

					var json = j;
					try {
						if (typeof (j) == "string")
							json = JSON.parse(j);
					} catch (ex) {
						// return;
					}

					if (!json || json.resultCode != "1") {
						return;
					}
					if (!json.data || !json.data.length) {
						return;
					}
					fn.showShareImage(json.data);
				},
				"error" : function(XMLHttpRequest, textStatus, errorThrown) {
					// alert("error");
				}
			});
		},

		showShareImage : function(photos) {
			var html = [];
			for (var i = 0; i < photos.length; i++) {
				var photo = photos[i];
				if (!photo)
					continue;
				html.push('<li class="shareImg"><img src="' +  photo.path
						+ '" alt=""></li>');
			}
			$('#shareList').html(html.join(""));
		},

	}; // end of fn

	var events = function() {
		var el_top_center = $('.top-center'), el_weath_bd = $('#weath-bd');

		$('#btnCommon').on('click', 'li#btnAdd img', function(event) {
			if (window.g_rotating) {
				rotate_stop();
				fn.deleteTagHide();
				event.stopPropagation();
				return;
			}

			$('#myModal').modal('show');
			event.stopPropagation();
		});
		$('#btnDelete img').on('click', function(event) {
			if (!window.g_rotating) {
				rotate_start();
				// $("#colleList .deleteTag").css("visibility", "visible");
				fn.deleteTagShow();

			} else {
				rotate_stop();
				// $("#colleList .deleteTag").css("visibility", "hidden");
				fn.deleteTagHide();
			}
			event.stopPropagation();

		});
		$(window).on('click', function(event) {
			if (window.g_rotating) {
				rotate_stop();
				fn.deleteTagHide();
				event.stopPropagation();
			}
		});

		$('#btnSave').on('click', function() {
			fn.saveCollection();
		});
		$('#colleList').on('click', 'li.link', function(e) {

			if (window.g_rotating) {

				if (!$(e.target).hasClass("glyphicon-remove")) {
					rotate_stop();
					fn.deleteTagHide();
					return;
				}

				var link = $(this);
				//var url = link.data('url');
				var url = link.attr('linkUrl');
				var title = link.data('title');

				var url2 = url;
				var title2 = title; // 闭包问题
				window._g_d_w_url = url;
				window._g_d_w_title = title;
				// alert("confirm..."+ url2);

				fn.deleteAndReshow();

				/*
				 * var confirm = $.scojs_confirm({ "content" : "是否要删除 " + title +
				 * "(" + url + ") ?", // "target" : "confirm_modal_chinese",
				 * action : (function(url3, title3) { // alert("action..." +
				 * url3); return function() {
				 * 
				 * this.close(); // alert("delete..." + url3);
				 * 
				 * fn.deleteAndReshow(); } })(url2, title2)
				 * 
				 * }); confirm.show();
				 */

				return;
			}
//			if (e.target.tagName == "IMG") {
//				window.location.href = $(this).attr('data-url');
//			}
		});

		$('#fold').on('click', function() {
			var that = this;

			fn.handlerWeathDisplay(function() {
				el_weath_bd.slideDown('slow', function() {
					$(that).attr('src', imagePath+"iconfont-fold.png");
				});
				el_top_center.hide();
			}, function() {
				el_weath_bd.slideUp('slow', function() {
					$(that).attr('src', imagePath+"iconfont-unfold.png");
					el_top_center.show();
				});
			});
		});
		$('#cityName').parent().on('taphold', function(e) {
			$(this).hide();
			e.preventDefault();
			// alert(e.type)
		});

		$('#cityName').parent().on('click', function(e) {
			// alert(e.type)
			var that = this;
			fn.setForSelectCity();
			$("#autocompleteInput").val($('#cityName').html());
			$('#myModalCity').modal('show');
			// $('#autocompleteInput').val($('#cityName').text());
			// $('#autocompleteInput').removeClass('hide');
		});
		
		
				
		$("#btnSaveCity").on('click', function() { // 获取文本框的实际值
			var city = $("#autocompleteInput").val().trim();
			if (city) {
				if (city != $('#cityName').html()) {
					vrv.weather.view.setWeatherData(city);
				}
				// alert(city);
				$('#myModalCity').modal('hide');
			}
		});

		$("#btnGetGpsCity").on('click', function() {
	        if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
	        	function connectWebViewJavascriptBridge(callback) {
	    	        if (window.WebViewJavascriptBridge) {
	    	            callback(WebViewJavascriptBridge);
	    	        } else {
	    	            document.addEventListener(
	    	                'WebViewJavascriptBridgeReady'
	    	                , function() {
	    	                    callback(WebViewJavascriptBridge);
	    	                },
	    	                false
	    	            );
	    	        }
	    	    }
	        	
	        	connectWebViewJavascriptBridge(function(bridge) {
	                bridge.callHandler('getLocation', {}, function(response) {
	                	if(response.length > 0){
							var mapStrJson = $.parseJSON(response);
		                	$('#autocompleteInput').val(mapStrJson.city);
	                	}else{
	                		$('#autocompleteInput').val("北京市");
	                	}
	                });
	            })
	        } else if (browser.versions.android) {
	        	var mapStr = native.getmap();
				if(mapStr.length > 0){
					var mapStrJson = $.parseJSON(mapStr);
					$('#autocompleteInput').val(mapStrJson.city);
				}else{
					$('#autocompleteInput').val("北京市");
				}
	        }
			/*vrv.gps.init(function(o) {
				$('#autocompleteInput').val(o.name);
			});*/
		});

	};

	var init = function() {
		//window.png1x1data = "";

		//fn.initWeatherTypes();

		events();
		// 加载收藏
		try {
			/*fn.initLocalData();
			fn.getLocalData(function(data) {
				if (data) {
					this.loadToView_Collection(data);
				}
			});*/
		} catch (ex) {
		}

		// 加载分享图片
		try {
			fn.loadShareImages();
		} catch (ex) {
			console.log(ex);
		}

		// 加载天气
	};

	window.modalAlert = function(content, title) {
		alert(content);
		// gDialog.fAlert(content);
		return false;

		try {
			$('#myModalAlertTitle').html(title);
			$('#myModalAlertContent').html(content);
			$('#myModalAlert').modal({
				backdrop : true,
				keyboard : true,
				show : true
			});
			return false;
		} catch (ex) {
			alert(title + "\n" + content);
		}
	};

	init();

	// getGpsCity(39.99, 116.33);

	// startGetLocationAndCity();

})(window);

// 为晃动
g_rotating = false;
function rotate_state1() {
	if (!g_rotating) {
		rotate_stop();
		return;
	}
	$(".rotate").removeClass("rotate_r2");
	$(".rotate").addClass("rotate_r1");
	setTimeout(rotate_state2, 500);
}
function rotate_state2() {
	if (!g_rotating) {
		rotate_stop();
		return;
	}
	$(".rotate").removeClass("rotate_r1");
	$(".rotate").addClass("rotate_r2");
	setTimeout(rotate_state1, 500);
}
function rotate_stop() {
	g_rotating = false;
	$(".rotate").removeClass("rotate_r1");
	$(".rotate").removeClass("rotate_r2");
}
function rotate_start() {
	g_rotating = true;
	rotate_state1();
}

var vrv = vrv || {};
/** 天气数据对象 M*/
vrv.weather = {
		
		weatherObj: {
			entity:{
				cityName:"",
				temp:"",
				code:"",
				image:"",
				desc:"",
				// 能见度
				visibility:"",
				subitem :{}
			},
			
			setCityName: function(_cityName){
				this.entity.cityName = _cityName;
			},
			
			setTemp: function(_temp){
				this.entity.temp = _temp;
			}, 
			
			setCode: function(_code){
				this.entity.code = _code;
				this.setImage(_code);
				this.setDesc(_code);
			},
			
			setVisibility: function(_visibility){
			
				
				this.entity.visibility = _visibility;
			},
			
			setImage:function(_code){
				this.entity.image = vrv.weather.getImage(_code);
			},
			setFc: function(_fc){
				this.entity.fc = _fc;
			},
			
			setDesc: function(_code){
				this.entity.desc =  vrv.weather.znDesc[_code];
			},
			
			setSubitem:function(key, val){
				this.entity.subitem[key] = val;
			},
			
			getObj :function(){ 
				return this.entity;
			}
			
		},
		
		baseYahooURL:"https://query.yahooapis.com/v1/public/yql?q=",
		
		unit : "c",
		
		myCallFn:"",
		
		
		getWoeid: function(city, callFn) {
		
			myCallFn = callFn || {};
			var _city = city || "北京";
			vrv.weather.weatherObj.setCityName(_city);
//		    var woeidYQL = 'select * from weather.forecast where woeid in (select woeid from geo.placefinder where text="' + _city + '")&format=json';
		    var woeidYQL = 'select woeid from geo.places(1) where text="' + _city + '"&format=json';
			var jsonURL = vrv.weather.baseYahooURL + woeidYQL;
		    $.getJSON(jsonURL, vrv.weather.woeidDownloaded);
		},
		
		woeidDownloaded:function(data) {
		    var woeid = null;
		    if (data.query.count <= 0) {
		    	 vrv.weather.weatherObj.setCode(999);
		        return;
		    } else if (data.query.count == 1) {
		        woeid = data.query.results.place.woeid;
		    } else {
		        woeid = data.query.results.place[0].woeid;
		    }
		    vrv.weather.getWeatherInfo(woeid);
		},
		
		getWeatherInfo: function(woeid) {
		    var weatherYQL = 'select * from weather.forecast where woeid=' + woeid + ' and u = "' + vrv.weather.unit + '" &format=json';
		    var jsonURL = vrv.weather.baseYahooURL + weatherYQL
		    $.getJSON(jsonURL, vrv.weather.weaterInfoDownloaded);
		},

		 weaterInfoDownloaded: function(data, callFn) {
		   /* vrv.weather.weatherObj.setTemp(data.query.results.channel.item.condition.temp);
		    vrv.weather.weatherObj.setCode(data.query.results.channel.item.condition.code);
		    vrv.weather.weatherObj.setVisibility(data.query.results.channel.atmosphere.visibility + data.query.results.channel.units.distance)
		    for (var i = 0; i <= 4; i++) {
		        var fc = data.query.results.channel.item.forecast[i];
		        var childEntity = {fcDay : fc.day, low: fc.low, high: fc.high, img: vrv.weather.getImage(fc.code), desc: vrv.weather.znDesc[fc.code]};
		        vrv.weather.weatherObj.setSubitem(i, childEntity);
		    }
		    
		    myCallFn.call(this, vrv.weather.weatherObj.getObj());*/
			// 华氏度转摄氏度 
			var temp =  data.query.results.channel.item.condition.temp
			if ("F" == data.query.results.channel.units.temperature){
				temp = Math.round((5/9)*(temp-32));
			}
		    vrv.weather.weatherObj.setTemp(temp);
		    vrv.weather.weatherObj.setCode(data.query.results.channel.item.condition.code);
		    vrv.weather.weatherObj.setVisibility(data.query.results.channel.atmosphere.visibility + data.query.results.channel.units.distance)
		    for (var i = 0; i <= 4; i++) {
		        var fc = data.query.results.channel.item.forecast[i];
		        var low = fc.low;
		        var high = fc.high
		        if ("F" ==  data.query.results.channel.units.temperature){
		        	low = Math.round((5/9)*(low-32));
		        	high = Math.round((5/9)*(high-32));
				}
		        var childEntity = {fcDay : fc.day, low: low, high: high, img: vrv.weather.getImage(fc.code), desc: vrv.weather.znDesc[fc.code]};
		        vrv.weather.weatherObj.setSubitem(i, childEntity);
		    }
		    
		    myCallFn.call(this, vrv.weather.weatherObj.getObj());
		},
		
		getZNDesc: function(code) {
			return this.znDesc[code];
		},
		
		znDesc:{
			0: messages.tornado,1:messages.tropStorm,2: messages.storm,3: messages.thundStorm,4: messages.thundShower,5: messages.sleet,6: messages.tornado,7: messages.snowHail,8: messages.mistyRain,9: messages.drizzle,
			10: messages.iceRain,11: messages.rainShower,12: messages.snowShower,13: messages.snowShower,14: messages.lightShower,15: messages.tornado,16: messages.blowSnow,17: messages.hail,18: messages.glaze,19: messages.dust,
			20: messages.fog,21: messages.mist,22: messages.smoke,23: messages.heavyWind,24: messages.wind,25: messages.cold,26: messages.cloudyYin,27: messages.cloudy,28: messages.cloudy,29: messages.isoCloudy,
			30: messages.isoCloudy,	31: messages.fair,32:  messages.fair,33: messages.clear,34: messages.clear,35: messages.rainHail,36: messages.hot,37: messages.isoStorms,38: messages.fewStorms,39: messages.fewStorms,
			40: messages.fewShowers,41: messages.heavySnow,42: messages.snowShowers,43: messages.heavySnow,44: messages.isoCloudy,45: messages.thundShower,46:messages.snowShower,47: messages.latedStorms,999: messages.serverError
		},
		
		visibilityDesc:{
			1:'20-30'+messages.kilometer,2:'15-25'+messages.kilometer,3:'10-20'+messages.kilometer,4:'5-15'+messages.kilometer,5:'1-10'+messages.kilometer,6:'0.3-1'+messages.kilometer,7:messages.less+'0.3'+messages.kilometer,8:messages.less+'0.1'+messages.kilometer
		},
		
		
		
		getImage: function(code){
			
			if (!code || code > 47){
				code = 999;
			}
			
			var image = basePath + '/resource/images/weathericons/'+code+'.png';
			return image;
		}
		
};



/** 天气视图设置 vc*/
vrv.weather.view = {
	init: function() {
		this.btn.init();
	},
	
	btn: {
		init: function(){
			this.toShareBtn();
		},
		
		/** 分享按钮*/
		toShareBtn: function(){
			$('.share').click(function() {
				var userToken = localStorage.getItem("userTonken");
				var lang = localStorage.getItem("lang");
				var action = 'feed.do?userToken='+userToken+'&lang='+lang;
				base.getAction(action);
			});
		}
	},
	
	util : {
		isNullOrEmpty : function(val) {
			return val == null || val == undefined || val == "";
		},
	},
	
	TemCache :{
		set : function(key, val) {
			if (vrv.weather.view.util.isNullOrEmpty(key)) // util.isNullOrEmpty(val) ||
				return false;

			localStorage.setItem(key, JSON.stringify(val));
			return true
		},
		get : function(key) {
			return JSON.parse(localStorage.getItem(key));
		}
	},

	setWeatherData:function(cityName){
		vrv.weather.getWoeid(cityName, function(o){
		
			vrv.weather.view.loadToView_curTemp(o);
			
		});
		
	},
	
	getWeatherBg : function(w) {
		var pic = [ "1", "2", "3", "8", "6", "4", "5", "9" ];
		var wea = [ messages.fair, messages.fog, messages.cloudyYin, messages.rain, messages.snow, messages.thunder, messages.sand, messages.haze];
		var result = "3";// 阴
		if(w == null){
			result = "1";
		}else{
			for (var i = 0; i < wea.length; i++) {
				if (w.indexOf(wea[i]) >= 0)
					result = pic[i];
			}
		}
		return  basePath + '/resource/images/weatherbg/' + result + "_3.jpg";
	},
	
	// 载入天气信息到页面
	loadToView_curTemp : function(temp) {
		
		/*if (util.isNullOrEmpty(temp)){
			return;
		}*/
		// 
		var _code = temp.code;
		
		// 温度
		var _temp = temp.temp;
		// 城市名称
		var _cityName = temp.cityName;
		// 图片
		var _icon = temp.image;
		// 描述
		var _desc = temp.desc;
		var _visibility = temp.visibility;
		var bgImage = vrv.weather.view.getWeatherBg(_desc);
		
		// 组织星期数据
		var dayNames = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");  
		Stamp = new Date();
		// 获取当天星期几
		var cToday = dayNames[Stamp.getDay()];
		var index;
		// 获取雅虎天气 ：记录当天星期的下标
		$.each(temp.subitem, function(i, v){
		    if (v.fcDay == cToday){
		    	index = i;
		    	return false;
		    }
		});
		
		// 获取明天天气对象
	    var tomorrow = temp.subitem[parseInt(index)+1];
	    // 获取后天天气对象
	    var alfterTomorrow = temp.subitem[parseInt(index)+2];
	    var tk = messages[tomorrow.fcDay];
	    var atk = messages[alfterTomorrow.fcDay];
	    $('#tomorrow').text(tk);
	    $('#afterTomorrow').text(atk);
	    
		$('#cityName').html(_cityName);
		$('#curTemperatue').html(_temp == "?" ? "" : _temp + "°");
		$('#weatherIcon')[0].src = _icon;
		
		$('#curTemperatueSmall').html(
				_temp == "?" ? "" : _temp + "°");
		$('#weatherIconSmall')[0].src =  _icon;

		$('#curWeather').html(_desc);
		$('#curWeatherSmall').html(_desc);
		
		$('#aqi').html(_visibility);
		$('.weathers').css("background-image","url(" + bgImage + ")");
		
		$('#tempRegion_tomorrow').html(tomorrow.low + "°~" + tomorrow.high + "°");
		$('#tempRegion_aflterTomorrow').html(alfterTomorrow.low + "°~" + alfterTomorrow.high + "°");
		
		$('#type_tomorrow>img')[0].src = tomorrow.img;
		$('#type_aflterTomorrow>img')[0].src = alfterTomorrow.img;
		
	},
	
		
}







